package com.huanong.it.fooder.service.impl;

import com.huanong.it.fooder.dto.ShoppingCartDTO;
import com.huanong.it.fooder.entity.ShoppingCart;
import com.huanong.it.fooder.entity.User;
import com.huanong.it.fooder.repository.ShoppingCartRepository;
import com.huanong.it.fooder.repository.UserRepository;
import com.huanong.it.fooder.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartRepository shoppingCartRepository;

    @Autowired
    private UserRepository userRepository; // 注入用户仓库

    /**
     * 创建新的购物车
     *
     * @param shoppingCartDTO 包含购物车信息的DTO
     * @return 创建的购物车的DTO
     */
    @Override
    public ShoppingCartDTO createShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart = new ShoppingCart();

        // 根据 userId 查找用户
        User user = userRepository.findById(shoppingCartDTO.getUserId())
                .orElseThrow(() -> new RuntimeException("User not found"));

        // 设置购物车的用户
        shoppingCart.setUser(user);

        // 保存购物车并返回DTO
        ShoppingCart savedShoppingCart = shoppingCartRepository.save(shoppingCart);
        return convertToDTO(savedShoppingCart);
    }

    /**
     * 根据ID获取购物车
     *
     * @param id 购物车的ID
     * @return 购物车的DTO
     */
    @Override
    public ShoppingCartDTO getShoppingCartById(Long id) {
        ShoppingCart shoppingCart = shoppingCartRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Shopping cart not found"));
        return convertToDTO(shoppingCart);
    }

    /**
     * 获取所有购物车
     *
     * @return 所有购物车的DTO列表
     */
    @Override
    public List<ShoppingCartDTO> getAllShoppingCarts() {
        List<ShoppingCart> shoppingCarts = shoppingCartRepository.findAll();
        return shoppingCarts.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    /**
     * 更新购物车
     *
     * @param id              购物车的ID
     * @param shoppingCartDTO 包含更新信息的DTO
     * @return 更新后的购物车的DTO
     */
    @Override
    public ShoppingCartDTO updateShoppingCart(Long id, ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart = shoppingCartRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Shopping cart not found"));

        // 更新用户（如果需要）
        if (!shoppingCart.getUser().getId().equals(shoppingCartDTO.getUserId())) {
            User user = userRepository.findById(shoppingCartDTO.getUserId())
                    .orElseThrow(() -> new RuntimeException("User not found"));
            shoppingCart.setUser(user);
        }

        // 这里可以添加更新购物车项的逻辑
        // 例如：更新购物车中的商品、数量等

        // 保存更新后的购物车并返回DTO
        ShoppingCart updatedShoppingCart = shoppingCartRepository.save(shoppingCart);
        return convertToDTO(updatedShoppingCart);
    }

    /**
     * 删除购物车
     *
     * @param id 购物车的ID
     */
    @Override
    public void deleteShoppingCart(Long id) {
        shoppingCartRepository.deleteById(id);
    }

    /**
     * 将ShoppingCart实体转换为ShoppingCartDTO
     *
     * @param shoppingCart 购物车实体
     * @return 转换后的购物车DTO
     */
    private ShoppingCartDTO convertToDTO(ShoppingCart shoppingCart) {
        ShoppingCartDTO dto = new ShoppingCartDTO();
        dto.setId(shoppingCart.getId());
        dto.setUserId(shoppingCart.getUser().getId());
        // 如果需要，可以在这里设置购物车项
        // dto.setItems(shoppingCart.getItems().stream().map(this::convertToItemDTO).collect(Collectors.toList()));
        return dto;
    }

    // 如果需要，可以添加一个方法将CartItem转换为DTO
    // private CartItemDTO convertToItemDTO(CartItem cartItem) {
    //     // 转换逻辑
    // }
}
